// src/utils/api.js - 重构版API工具
import io from 'socket.io-client'

const API_BASE_URL = 'http://localhost:5000'

class ApiService {
  constructor() {
    this.baseURL = API_BASE_URL
    this.socket = null
  }

  // 通用请求方法
  async request(endpoint, options = {}) {
    const url = `${this.baseURL}${endpoint}`
    const config = {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers
      },
      ...options
    }

    console.log(`API请求: ${config.method || 'GET'} ${url}`)

    try {
      const response = await fetch(url, config)
      
      if (!response.ok) {
        const errorText = await response.text()
        let errorMessage = `HTTP ${response.status}: ${response.statusText}`
        
        try {
          const errorJson = JSON.parse(errorText)
          errorMessage = errorJson.error || errorMessage
        } catch (e) {
          errorMessage = errorText || errorMessage
        }
        
        throw new Error(errorMessage)
      }

      // 根据响应类型处理
      const contentType = response.headers.get('content-type') || ''
      
      if (contentType.includes('audio/')) {
        return await response.blob()
      } else if (contentType.includes('application/json')) {
        return await response.json()
      } else {
        return await response.text()
      }
      
    } catch (error) {
      console.error('API请求失败:', error)
      throw error
    }
  }

  // GET请求
  async get(endpoint) {
    return this.request(endpoint, { method: 'GET' })
  }

  // POST请求
  async post(endpoint, data = {}) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // 文件上传
  async uploadFile(endpoint, formData) {
    return this.request(endpoint, {
      method: 'POST',
      body: formData,
      headers: {} // 让浏览器自动设置Content-Type
    })
  }

  // WebSocket连接
  connectSocket() {
    if (this.socket) {
      return this.socket
    }

    console.log('连接WebSocket:', API_BASE_URL)
    
    this.socket = io(API_BASE_URL, {
      autoConnect: true,
      reconnection: true,
      reconnectionDelay: 1000,
      reconnectionAttempts: 5
    })

    this.socket.on('connect', () => {
      console.log('WebSocket连接成功')
    })

    this.socket.on('disconnect', (reason) => {
      console.log('WebSocket断开:', reason)
    })

    this.socket.on('connect_error', (error) => {
      console.error('WebSocket连接错误:', error)
    })

    return this.socket
  }

  // 断开WebSocket
  disconnectSocket() {
    if (this.socket) {
      this.socket.disconnect()
      this.socket = null
    }
  }
}

// 创建API服务实例
const apiService = new ApiService()

// 具体API方法
export const api = {
  // 健康检查
  healthCheck: () => apiService.get('/api/health'),

  // 简历上传
  uploadResume: (jobPosition, resumeFile) => {
    const formData = new FormData()
    formData.append('job_position', jobPosition)
    formData.append('resume', resumeFile)
    return apiService.uploadFile('/api/upload-resume', formData)
  },

  // 身份验证
  verifyIdentity: (sessionId) => 
    apiService.post(`/api/verify-identity/${sessionId}`),

  // 人脸验证
  captureFace: (sessionId, imageData) => 
    apiService.post(`/api/capture-face/${sessionId}`, { image: imageData }),

  // 开始面试
  startInterview: (sessionId) => 
    apiService.post(`/api/start-interview/${sessionId}`),

  // 语音合成
  synthesizeSpeech: async (text) => {
    try {
      const response = await fetch(`${API_BASE_URL}/api/synthesize-speech`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text })
      })

      if (!response.ok) {
        throw new Error(`语音合成失败: ${response.status}`)
      }

      const contentType = response.headers.get('content-type') || ''
      
      if (contentType.includes('audio/')) {
        return await response.blob()
      } else {
        const data = await response.json()
        return data
      }
    } catch (error) {
      console.error('语音合成错误:', error)
      throw error
    }
  },

  // 获取语音识别结果
  getRecognitionResult: (sessionId) => 
    apiService.get(`/api/get-recognition-result/${sessionId}`),

  // WebSocket相关
  socket: {
    connect: () => apiService.connectSocket(),
    disconnect: () => apiService.disconnectSocket(),
    
    emit: (event, data) => {
      const socket = apiService.connectSocket()
      console.log('Socket发送:', event, data)
      socket.emit(event, data)
    },

    on: (event, callback) => {
      const socket = apiService.connectSocket()
      console.log('Socket监听:', event)
      socket.on(event, callback)
    },

    off: (event, callback) => {
      const socket = apiService.connectSocket()
      socket.off(event, callback)
    }
  }
}

// WebSocket事件常量
export const SOCKET_EVENTS = {
  CONNECT: 'connect',
  DISCONNECT: 'disconnect',
  JOIN_SESSION: 'join_session',
  START_FIRST_ROUND: 'start_first_round',
  SKIP_QUESTION: 'skip_question',
  QUESTION_START: 'question_start',
  AUDIO_FINISHED: 'audio_finished',
  TIMER_START: 'timer_start',
  TIMER_UPDATE: 'timer_update',
  TIMER_END: 'timer_end',
  INTERVIEW_COMPLETED: 'interview_completed',
  ERROR: 'error'
}

// 工具函数
export const utils = {
  // 文件转base64
  fileToBase64: (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = reject
    })
  },

  // 检查文件类型
  isValidImageFile: (file) => {
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png']
    return validTypes.includes(file.type)
  },

  // 检查文件大小
  isValidFileSize: (file, maxSize = 10 * 1024 * 1024) => {
    return file.size <= maxSize
  },

  // 格式化文件大小
  formatFileSize: (bytes) => {
    if (bytes === 0) return '0 Bytes'
    const k = 1024
    const sizes = ['Bytes', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  },

  // 格式化时间
  formatTime: (seconds) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  },

  // 检查浏览器能力
  checkBrowserCapabilities: () => {
    return {
      getUserMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
      webSocket: !!window.WebSocket,
      canvas: !!document.createElement('canvas').getContext,
      fileApi: !!(window.File && window.FileReader && window.FileList && window.Blob),
      audioContext: !!(window.AudioContext || window.webkitAudioContext)
    }
  },

  // 播放音频Blob
  playAudioBlob: (audioBlob, audioElement) => {
    return new Promise((resolve, reject) => {
      try {
        const audioUrl = URL.createObjectURL(audioBlob)
        
        const cleanup = () => {
          URL.revokeObjectURL(audioUrl)
          audioElement.removeEventListener('ended', handleEnded)
          audioElement.removeEventListener('error', handleError)
        }
        
        const handleEnded = () => {
          cleanup()
          resolve(true)
        }
        
        const handleError = (e) => {
          cleanup()
          reject(new Error('音频播放失败'))
        }
        
        audioElement.addEventListener('ended', handleEnded)
        audioElement.addEventListener('error', handleError)
        
        audioElement.src = audioUrl
        audioElement.play().catch(reject)
        
      } catch (error) {
        reject(error)
      }
    })
  }
}

export default apiService